<template>
  <div class="home-container">
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧内容区域（教职工视角完整，拉满并公告填充） -->
      <el-col :span="16">
        <div class="left-column">
        <!-- 欢迎卡片（Hero） -->
        <el-card class="welcome-card" style="margin-bottom: 20px;">
          <template #header>
            <span>欢迎</span>
          </template>
          <div class="welcome-hero">
            <div class="hero-left">
              <div class="hero-title">
                欢迎来到学工管理系统
                <el-tag class="hero-role-tag" size="small" type="info" effect="plain">{{ roleName }}</el-tag>
              </div>
              <div class="hero-subtitle">您好，{{ nickname }}。以下是为您准备的快速入口：</div>
              <div class="hero-actions">
                <el-button type="primary" @click="navigateTo('/main/query')">
                  <el-icon style="margin-right:6px"><Search /></el-icon>
                  信息查询
                </el-button>
                <el-button type="warning" @click="navigateTo('/main/leave')">
                  <el-icon style="margin-right:6px"><Document /></el-icon>
                  请假审批
                </el-button>
                <el-button type="success" @click="navigateTo('/main/scholarship')">
                  <el-icon style="margin-right:6px"><Trophy /></el-icon>
                  奖学金管理
                </el-button>
              </div>
            </div>
            <div class="hero-right">
              <div class="hero-graphic">
                <el-icon size="56" color="#409eff">
                  <Document />
                </el-icon>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 统计概览（非学生角色） -->
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="8">
            <el-card class="stat-card" @click="navigateTo('/main/leave')">
              <div class="stat-content">
                <el-icon size="28" color="#e6a23c"><Bell /></el-icon>
                <div class="stat-text">
                  <div class="stat-title">请假待审批</div>
                  <div class="stat-value">{{ stats.leavePending }} 条</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card" @click="navigateTo('/main/scholarship')">
              <div class="stat-content">
                <el-icon size="28" color="#67c23a"><CircleCheck /></el-icon>
                <div class="stat-text">
                  <div class="stat-title">奖学金待审核</div>
                  <div class="stat-value">{{ stats.scholarshipPending }} 条</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card" @click="navigateTo('/main/query')">
              <div class="stat-content">
                <el-icon size="28" color="#409eff"><Document /></el-icon>
                <div class="stat-text">
                  <div class="stat-title">信息变更待确认</div>
                  <div class="stat-value">{{ stats.infoChanges }} 条</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 最新公告（教职工） -->
        <el-card class="announcement-card">
          <template #header>
            <div class="card-header">
              <span>最新公告</span>
              <el-button type="text" @click="navigateTo('/main/query')">更多</el-button>
            </div>
          </template>
          <ul class="announcement-list">
            <li v-for="item in announcements" :key="item.id" class="announcement-item">
              <span class="ann-title">{{ item.title }}</span>
              <span class="ann-date">{{ item.date }}</span>
            </li>
          </ul>
        </el-card>
        </div>
      </el-col>

      <!-- 右侧内容区域（共享日历与事件，拉满右侧） -->
      <el-col :span="8">
        <div class="right-column">
        <!-- 自定义日历组件 -->
        <el-card class="calendar-card" style="margin-bottom: 20px;">
          <div class="custom-calendar">
            <!-- 日历头部 -->
            <div class="calendar-header">
              <div class="calendar-title">
                {{ formatCalendarTitle(calendarValue) }}
              </div>
              <div class="calendar-controls">
                <button class="nav-btn" @click="previousMonth">‹</button>
                <button class="nav-btn" @click="goToToday">今天</button>
                <button class="nav-btn" @click="nextMonth">›</button>
              </div>
            </div>

            <!-- 星期标题 -->
            <div class="weekdays">
              <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
            </div>

            <!-- 日期网格 -->
            <div class="calendar-grid">
              <div
                v-for="day in calendarDays"
                :key="`${day.date}-${day.day}`"
                class="calendar-day"
                :class="{
                  'is-current-month': day.isCurrentMonth,
                  'is-today': day.isToday,
                  'is-selected': day.isSelected,
                  'has-event': day.hasEvent
                }"
                @click="selectDate(day)"
              >
                <span class="day-number">{{ day.day }}</span>
                <div v-if="day.hasEvent" class="event-dot"></div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 即将到来的事件 -->
        <el-card class="events-card">
          <template #header>
            <div class="card-header">
              <span>即将到来的事件</span>
            </div>
          </template>
          <div class="upcoming-events">
            <div v-for="event in upcomingEvents" :key="event.id" class="event-item">
              <div class="event-content">
                <div class="event-title">{{ event.title }}</div>
                <div class="event-description">{{ event.description }}</div>
                <div class="event-meta">
                  <span class="event-date">{{ event.date }}</span>
                  <span class="event-duration">{{ event.duration }}</span>
                </div>
              </div>
              <div class="event-icon">
                <el-icon color="#409eff">
                  <Document />
                </el-icon>
              </div>
            </div>
            <div class="view-all-link">
              <el-button type="text" style="color: #e6a23c;">查看所有即将到来的事件 ></el-button>
            </div>
          </div>
        </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Document, Search, Trophy, Bell, CircleCheck } from '@element-plus/icons-vue'

// 角色信息
let localUser: any = {}
try {
  const raw = localStorage.getItem('userInfo')
  localUser = raw ? JSON.parse(raw) : {}
} catch (e) {
  localUser = {}
}
const roleId = Number(localUser?.roleId) || 0
const roleMap: Record<number, string> = {
  1: '系统管理员',
  2: '辅导员',
  3: '老师',
  4: '学生'
}
const roleName = roleMap[roleId] || '用户'
const nickname = localUser?.nickname || '用户'

const router = useRouter()
const navigateTo = (path: string) => {
  router.push(path)
}

// 示例数据（后续可接入接口）
const stats = {
  leavePending: 3,
  scholarshipPending: 1,
  infoChanges: 2
}

const announcements = [
  { id: 1, title: '关于期末考试安排通知', date: '2024-01-18' },
  { id: 2, title: '奖学金评定工作安排', date: '2024-01-12' },
  { id: 3, title: '寒假学生返校须知', date: '2024-01-08' }
]

// 日历相关数据（与学生视角共享）
const calendarValue = ref(new Date())
const selectedDate = ref(new Date())
const weekdays = ['一', '二', '三', '四', '五', '六', '日']

// 即将到来的事件数据
const upcomingEvents = ref([
  { id: 1, title: '请假审批会议', description: '教学楼 302 会议室', date: '19 Jan', duration: '45 分钟' },
  { id: 2, title: '奖学金评审', description: '行政楼 205 会议室', date: '20 - 21 Jan', duration: '3 小时' },
  { id: 3, title: '教学工作例会', description: '行政楼 201', date: '22 Jan', duration: '50 分钟' }
])

const eventDates = ['2024-01-19', '2024-01-20', '2024-01-21', '2024-01-22']

const hasEvent = (date: string | undefined) => {
  if (!date) return false
  try {
    const dateObj = new Date(date)
    const formattedDate = dateObj.toISOString().split('T')[0]
    return formattedDate ? eventDates.includes(formattedDate) : false
  } catch (error) {
    console.warn('Invalid date format:', date)
    return false
  }
}

const calendarDays = computed(() => {
  const year = calendarValue.value.getFullYear()
  const month = calendarValue.value.getMonth()
  const today = new Date()

  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  const firstDayOfWeek = (firstDay.getDay() + 6) % 7
  const prevMonth = new Date(year, month, 0)
  const prevMonthDays = prevMonth.getDate()

  const days: any[] = []

  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const day = prevMonthDays - i
    const date = new Date(year, month - 1, day)
    days.push({
      day,
      date: date.toISOString().split('T')[0],
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      hasEvent: hasEvent(date.toISOString().split('T')[0])
    })
  }

  for (let day = 1; day <= lastDay.getDate(); day++) {
    const date = new Date(year, month, day)
    const dateStr = date.toISOString().split('T')[0]
    const isToday = date.toDateString() === today.toDateString()
    const isSelected = date.toDateString() === selectedDate.value.toDateString()

    days.push({
      day,
      date: dateStr,
      isCurrentMonth: true,
      isToday,
      isSelected,
      hasEvent: hasEvent(dateStr)
    })
  }

  const remainingDays = 42 - days.length
  for (let day = 1; day <= remainingDays; day++) {
    const date = new Date(year, month + 1, day)
    days.push({
      day,
      date: date.toISOString().split('T')[0],
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      hasEvent: hasEvent(date.toISOString().split('T')[0])
    })
  }

  return days
})

const formatCalendarTitle = (date: any) => {
  if (!date) return '未知日期'
  try {
    const dateObj = date instanceof Date ? date : new Date(date)
    const year = dateObj.getFullYear()
    const month = dateObj.getMonth() + 1
    return `${year}年${month}月`
  } catch (error) {
    console.warn('Invalid date format:', date)
    return '未知日期'
  }
}

const previousMonth = () => {
  const newDate = new Date(calendarValue.value)
  newDate.setMonth(newDate.getMonth() - 1)
  calendarValue.value = newDate
}

const nextMonth = () => {
  const newDate = new Date(calendarValue.value)
  newDate.setMonth(newDate.getMonth() + 1)
  calendarValue.value = newDate
}

const goToToday = () => {
  const today = new Date()
  calendarValue.value = today
  selectedDate.value = today
}

const selectDate = (day: any) => {
  if (day.isCurrentMonth) {
    selectedDate.value = new Date(day.date)
  }
}
</script>

<style scoped>
.home-container {
  padding: 0;
}

/* 右侧列拉满并让事件卡片填充剩余高度 */
.right-column {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 120px);
}

.events-card {
  display: flex;
  flex-direction: column;
  flex: 1; /* 占据剩余空间 */
}

.events-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
}
/* 左侧列拉满并让公告卡片填充剩余高度 */
.left-column {
  display: flex;
  flex-direction: column;
  /* 视口高度减去顶部导航等占用，可按需微调 */
  min-height: calc(100vh - 120px);
}

.announcement-card {
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  flex: 1; /* 占据剩余空间 */
}

.announcement-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto; /* 内容滚动 */
  padding-bottom: 0;
}

/* 欢迎卡片与动作区样式 */
.welcome-hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 240px;
  padding: 24px 28px;
  background: linear-gradient(135deg, #eaf3ff 0%, #f9fbff 60%, #ffffff 100%);
  border-radius: 10px;
}

.hero-left {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.hero-title {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.hero-role-tag {
  vertical-align: middle;
}

.hero-subtitle {
  font-size: 14px;
  color: #606266;
  max-width: 520px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.hero-actions {
  display: flex;
  gap: 10px;
  flex-wrap: nowrap;
  margin-top: 6px;
}

.hero-actions :deep(.el-button) {
  white-space: nowrap;
}

.hero-right {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.hero-graphic {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, #ecf5ff 0%, #e9f0ff 40%, #f2f6ff 70%, #ffffff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6px 18px rgba(64, 158, 255, 0.15);
}

/* 统计卡片样式 */
.stat-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-content {
  height: 100%;
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-text {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 18px;
  font-weight: 700;
  color: #303133;
}

/* 最新公告样式 */
.announcement-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.announcement-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.announcement-item:last-child {
  border-bottom: none;
}

.ann-title {
  color: #303133;
}

.ann-date {
  color: #909399;
  font-size: 12px;
}

/* 日历卡片与事件列表样式（共享） */
.calendar-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.calendar-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  color: #303133;
  font-weight: 600;
}

.calendar-card :deep(.el-card__body) {
  padding: 0;
  background: #fff;
}

.custom-calendar {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.calendar-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.calendar-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.nav-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

.nav-btn:active {
  background: #ecf5ff;
  border-color: #409eff;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.weekday {
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: #909399;
  border-right: 1px solid #e4e7ed;
}

.weekday:last-child {
  border-right: none;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #fff;
}

.calendar-day {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-right: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #606266;
}

.calendar-day:nth-child(7n) {
  border-right: none;
}

.calendar-day:hover {
  background: #f5f7fa;
}

.calendar-day.is-current-month {
  color: #303133;
  font-weight: 500;
}

.calendar-day:not(.is-current-month) {
  color: #c0c4cc;
  background: #fafafa;
}

.calendar-day.is-today {
  color: #409eff;
  font-weight: 600;
}

.calendar-day.is-today:not(.is-selected) {
  background: #ecf5ff;
}

.calendar-day.is-selected {
  background: #409eff;
  color: #fff;
  font-weight: 600;
}

.calendar-day.is-selected:hover {
  background: #337ecc;
}

.calendar-day.has-event {
  position: relative;
}

.calendar-day.has-event:not(.is-selected) {
  background: #fff7e6;
}

.calendar-day.has-event.is-selected {
  background: #409eff;
}

.day-number {
  font-size: 14px;
  line-height: 1;
}

.event-dot {
  position: absolute;
  bottom: 4px;
  left: 50%;
  transform: translateX(-50%);
  width: 4px;
  height: 4px;
  background-color: #e6a23c;
  border-radius: 50%;
}

.calendar-day.is-selected .event-dot {
  background-color: #fff;
}

.upcoming-events {
  max-height: 400px;
  overflow-y: auto;
}

.event-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.event-item:last-child {
  border-bottom: none;
}

.event-content {
  flex: 1;
  margin-right: 12px;
}

.event-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.event-description {
  color: #909399;
  font-size: 12px;
  margin-bottom: 6px;
  line-height: 1.4;
}

.event-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-date {
  color: #e6a23c;
  font-size: 12px;
  font-weight: 500;
}

.event-duration {
  color: #909399;
  font-size: 11px;
}

.event-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #f0f9ff;
  border-radius: 50%;
}

.view-all-link {
  text-align: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}
</style>